//
//  FLRecordedViewController.m
//  FeeLing
//
//  Created by 乔光玉 on 2019/1/10.
//  Copyright © 2019年 大仙儿飘. All rights reserved.
//
#import "FLRceondNameView.h"
#import <AVFoundation/AVFoundation.h>
#import "FLAudioObject.h"
#import "FLRecordedViewController.h"
#import "FLAudioObject.h"
#import "FLAudioMusicDBManager.h"
@interface FLRecordedViewController ()<UIGestureRecognizerDelegate>
{
    BOOL isfirstpan;
    NSTimer *_timer; //定时器
    NSString *filePath;
    FLRceondNameView * _mingchengview;
}
@property (nonatomic, strong)FLAudioObject * audioObject;
@property (nonatomic,assign) NSInteger countNum;//录音计时（秒）
@property(nonatomic,strong)UILabel * timeLabel;
@property (nonatomic, strong) AVAudioSession * session;
@property (nonatomic, strong) AVAudioRecorder * recorder;//录音器
@property (nonatomic, strong) AVAudioPlayer * player; //播放器
@property (nonatomic, strong) NSURL * recordFileUrl; //文件地址
@property(nonatomic,strong)UIButton *cancelbutton;
@property(nonatomic,strong)UIButton * turebutton;

@end

@implementation FLRecordedViewController
-(void)viewWillAppear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    
     self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    isfirstpan = YES;
    self.view.backgroundColor = [UIColor colorWithHexString:@"#2B2D5C"];
    UIImageView * imageview =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"录音背景"]];
    imageview.frame = CGRectMake(0, 73*SCREENHEIGHT/667, SCREENWIDTH, 147);
    [self.view addSubview:imageview];
    UILabel * addlabelone = [[UILabel alloc]init];
    addlabelone.frame = CGRectMake(0, 323*SCREENHEIGHT/667, SCREENWIDTH, 24);
    addlabelone.textAlignment = NSTextAlignmentCenter;
    addlabelone.textColor = [UIColor colorWithHexString:@"#FFFFFF"];
    addlabelone.font = [UIFont fontWithName:@"PingFangSC-Thin" size: 17];
    addlabelone.text = NSLocalizedString(@"audionotlabelonetext", nil);
    [self.view addSubview:addlabelone];
    
    UIView *bottomview = [[UIView alloc] init];
    bottomview.frame = CGRectMake(15,357*SCREENHEIGHT/667,SCREENWIDTH-30,270*(SCREENWIDTH-30)/345);
    
    bottomview.backgroundColor = [UIColor colorWithRed:36/255.0 green:35/255.0 blue:79/255.0 alpha:1.0];
    bottomview.layer.cornerRadius = 8;
    bottomview.clipsToBounds = YES;
    bottomview.userInteractionEnabled = YES;
    [self.view addSubview:bottomview];
    
    self.timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 54, bottomview.width, 22)];
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 16];
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    self.timeLabel.text = @"00:00";
    [bottomview addSubview:self.timeLabel];
    
    
    UIView *circleview1 = [[UIView alloc] init];
    circleview1.frame = CGRectMake(bottomview.width/2-70,86*(SCREENWIDTH-30)/345,140,140);
    
    
    // gradient
    CAGradientLayer *gl1 = [CAGradientLayer layer];
    gl1.frame = CGRectMake(0,0,140,140);
    gl1.startPoint = CGPointMake(0.5, 0);
    gl1.endPoint = CGPointMake(0.5, 1);
    gl1.colors = @[(__bridge id)[UIColor colorWithRed:126/255.0 green:139/255.0 blue:248/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:76/255.0 green:88/255.0 blue:233/255.0 alpha:1.0].CGColor];
    gl1.locations = @[@(0), @(1.0f)];
    gl1.cornerRadius = 70;
    [circleview1.layer insertSublayer:gl1 atIndex:0];
    
    [bottomview addSubview:circleview1];
    
    
    UIView *circleview2 = [[UIView alloc] init];
    circleview2.frame = CGRectMake(bottomview.width/2-60,circleview1.top+10,120,120);
    
    
    // gradient
    CAGradientLayer *gl2 = [CAGradientLayer layer];
    gl2.frame = CGRectMake(0,0,120,120);
    gl2.startPoint = CGPointMake(0.5, 0);
    gl2.endPoint = CGPointMake(0.5, 1);
    gl2.colors = @[(__bridge id)[UIColor colorWithRed:126/255.0 green:139/255.0 blue:248/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:76/255.0 green:88/255.0 blue:233/255.0 alpha:1.0].CGColor];
    gl2.locations = @[@(0), @(1.0f)];
    gl2.cornerRadius = 60;
    [circleview2.layer insertSublayer:gl2 atIndex:0];
    
    [bottomview addSubview:circleview2];
    
    
    UIView *circleview3 = [[UIView alloc] init];
    circleview3.frame = CGRectMake(bottomview.width/2-50,circleview2.top+10,100,100);
    
    
    // gradient
    CAGradientLayer *gl3 = [CAGradientLayer layer];
    gl3.frame = CGRectMake(0,0,100,100);
    gl3.startPoint = CGPointMake(0.5, 0);
    gl3.endPoint = CGPointMake(0.5, 1);
    gl3.colors = @[(__bridge id)[UIColor colorWithRed:126/255.0 green:139/255.0 blue:248/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:76/255.0 green:88/255.0 blue:233/255.0 alpha:1.0].CGColor];
    gl3.locations = @[@(0), @(1.0f)];
    gl3.cornerRadius = 50;
    [circleview3.layer insertSublayer:gl3 atIndex:0];
    
    [bottomview addSubview:circleview3];
    
    
    
    UIView *circleview4 = [[UIView alloc] init];
    circleview4.frame = CGRectMake(bottomview.width/2-40,circleview3.top+10,80,80);
    
    
    // gradient
    CAGradientLayer *gl4 = [CAGradientLayer layer];
    gl4.frame = CGRectMake(0,0,80,80);
    gl4.startPoint = CGPointMake(0.5, 0);
    gl4.endPoint = CGPointMake(0.5, 1);
    gl4.colors = @[(__bridge id)[UIColor colorWithRed:126/255.0 green:139/255.0 blue:248/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:76/255.0 green:88/255.0 blue:233/255.0 alpha:1.0].CGColor];
    gl4.locations = @[@(0), @(1.0f)];
    gl4.cornerRadius = 40;
    [circleview4.layer insertSublayer:gl4 atIndex:0];
    
    [bottomview addSubview:circleview4];
    
    UIImageView * luyin = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"录音大"]];
    luyin.frame = CGRectMake(bottomview.width/2-15, circleview4.top+20, 30, 41);
    [bottomview addSubview:luyin];
    
    _cancelbutton = [UIButton new];
    [_cancelbutton setImage:[UIImage imageNamed:@"录音大取消"] forState:UIControlStateNormal];
    _cancelbutton.frame = CGRectMake(10, 10, 39, 39);
    _cancelbutton.hidden = YES;
    [_cancelbutton addTarget:self action:@selector(cancelbuttonclick) forControlEvents:UIControlEventTouchUpInside];
    [bottomview addSubview:_cancelbutton];
    
    _turebutton = [UIButton new];
    _turebutton.hidden = YES;
    [_turebutton setImage:[UIImage imageNamed:@"录音大完成"] forState:UIControlStateNormal];
    _turebutton.frame = CGRectMake(bottomview.width-10-39, 10, 39, 39);
    [_turebutton addTarget:self action:@selector(turebuttonclick) forControlEvents:UIControlEventTouchUpInside];
    [bottomview addSubview:_turebutton];
    
    UIView *circleviewfirsttap = [[UIView alloc] init];
    circleviewfirsttap.frame = CGRectMake(bottomview.width/2-70,86*(SCREENWIDTH-30)/345,140,140);
    circleviewfirsttap.userInteractionEnabled = YES;
   UILongPressGestureRecognizer * longPressGest = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressView:)];
    longPressGest.delegate = self;
    longPressGest.minimumPressDuration = 1;
    [circleviewfirsttap addGestureRecognizer:longPressGest];
     [bottomview addSubview:circleviewfirsttap];
    
    
}
-(void)longPressView:(UILongPressGestureRecognizer *)longPressGest{
    
    NSLog(@"%ld",longPressGest.state);
    if (longPressGest.state==UIGestureRecognizerStateBegan) {
        if (isfirstpan) {
            isfirstpan = NO;
            dispatch_async(dispatch_get_main_queue(), ^{
                __weak typeof(self)weakSelf = self;
                [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {

                    if (granted) {
                        [weakSelf recorderButtonselectedwithbutton];
                    }else{
                        [weakSelf.navigationController popViewControllerAnimated:YES];
                    }
                }];

            });

        }
        NSLog(@"长按手势开启");
    }else if (longPressGest.state==UIGestureRecognizerStateEnded){
        
        
        if (self.countNum<30) {
            
            [self stopRecord:nil];
            
        }else{
            
            return;
        }
    }
    
    
}



-(void)cancelbuttonclick{
    
     [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
     [self.navigationController popViewControllerAnimated:YES];
}
//传入 秒  得到  xx分钟xx秒
-(NSString *)getMMSSFromSS:(NSInteger )seconds{
    
    
    
    //format of minute
    NSString *str_minute ;
    if (seconds/60>=10) {
        str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    }else{
        str_minute = [NSString stringWithFormat:@"0%ld",seconds/60];
    }
    
    //format of second
    NSString *str_second;
    if (seconds%60>=10) {
        str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    }else{
        str_second = [NSString stringWithFormat:@"0%ld",seconds%60];
    }
    
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    
    NSLog(@"format_time : %@",format_time);
    
    return format_time;
    
}
-(void)turebuttonclick{
    
    _mingchengview = [[FLRceondNameView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT)];
    
     __weak typeof(self) weakself = self;
    _mingchengview.cancelBlock = ^(UIButton * button) {
         __strong __typeof(self) strongSelf = weakself;
        [strongSelf->_mingchengview removeFromSuperview];
        [weakself.navigationController popViewControllerAnimated:YES];
    };
    
    _mingchengview.tureBlock = ^(UIButton * _Nonnull button, NSString * _Nonnull text) {
         __strong __typeof(self) strongSelf = weakself;
        if (text.length) {
            if ([[FLAudioMusicDBManager sharedManager] isExistAudio:text]) {
                
                [MBProgressHUD showError:NSLocalizedString(@"mingzichongfu", nil) toView:strongSelf->_mingchengview];
                
                
            }else{
                
                weakself.audioObject.name =text;
                NSURL *songURL = [NSURL fileURLWithPath:strongSelf->filePath];
                
                AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:songURL options:nil];
                //NSString * aac =[NSString stringWithFormat:@"%.2f",CMTimeGetSeconds(songAsset.duration)];
                weakself.audioObject.time =[weakself getMMSSFromSS:(int)CMTimeGetSeconds(songAsset.duration)];
                
                
                if ( [[FLAudioMusicDBManager sharedManager] insertAudioWith:weakself.audioObject]) {
                
                    [MBProgressHUD showError:NSLocalizedString(@"luyinbaocunchengg", nil) toView:strongSelf->_mingchengview];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                      
                        [strongSelf->_mingchengview removeFromSuperview];
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"makebee"object:@(0)];
                        [weakself.navigationController popToRootViewControllerAnimated:YES];
                        
                        
                    });
                    
                }else{
                   
                   [MBProgressHUD showError:NSLocalizedString(@"luyinbaocunshibai", nil) toView:strongSelf->_mingchengview];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        [strongSelf->_mingchengview removeFromSuperview];
                        
                        
                        [weakself.navigationController popToRootViewControllerAnimated:YES];
                        
                        
                    });
                    
                    
                }
                
            }
        }else{
            
            [MBProgressHUD showError:NSLocalizedString(@"pleaserut", nil) toView:strongSelf->_mingchengview];
        }
            
        
        
        
    };
    [self.view addSubview:_mingchengview];
    
}

- (void)stopRecord:(id)sender {
    _cancelbutton.hidden = NO;
    _turebutton.hidden = NO;
    [self removeTimer];
    NSLog(@"停止录音");
    NSLog(@"%@",self.recorder);
    if ([self.recorder isRecording]) {
        [self.recorder stop];
        [self.session setActive:NO error:nil];
        [self.session setCategory:AVAudioSessionCategoryPlayAndRecord  withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:nil ];
        [self.session setActive:YES error:nil];
    }
}
-(void)recorderButtonselectedwithbutton{
     [self addTimer];
    AVAudioSession *session =[AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord  withOptions:AVAudioSessionCategoryOptionDuckOthers error:nil ];
    if (session == nil) {
        NSLog(@"Error creating session: %@",[sessionError description]);
    }else{
        [session setActive:YES error:nil];
    }
    self.session = session;
    NSLog(@"%@",session);
    NSLog(@"%@",self.session);
    
    self.audioObject = nil;
    self.audioObject = [[FLAudioObject alloc]init];
    //1.获取沙盒地址
    NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"path == %@",path);
    NSString * time =[NSString stringWithFormat:@"%@",[self getCurrentTimes]];
    NSString * showname =[NSString stringWithFormat:@"/%@.wav",time];
    filePath = [path stringByAppendingString:showname];
    NSLog(@"filePath == %@",filePath);
    self.audioObject.localam = showname ;
    self.audioObject.name = time ;
    self.audioObject.type= 2;
    //2.获取文件路径
    self.recordFileUrl = [NSURL fileURLWithPath:filePath];
    //设置参数
    NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                                   //采样率  8000/11025/22050/44100/96000（影响音频的质量）
                                   [NSNumber numberWithFloat: 8000.0],AVSampleRateKey,
                                   // 音频格式 可以选择mp3格式 但是我选了。提示我不能使用
                                   [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                                   //采样位数  8、16、24、32 默认为16
                                   [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                   // 音频通道数 1 或 2
                                   [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
                                   //录音质量
                                   [NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey,
                                   nil];
    NSLog(@"%@",_recorder);
    /*初始化录音器 并且读取文件地址 */
    _recorder = [[AVAudioRecorder alloc] initWithURL:self.recordFileUrl settings:recordSetting error:nil];
    [_recorder peakPowerForChannel:0];
    NSLog(@"%@",_recorder);
    if (_recorder) {
        /*级计量或放假默认是关闭的*/
        _recorder.meteringEnabled = YES;
        /*创建文件,准备记录。会自动记录*/
        [_recorder prepareToRecord];
        /*启动或恢复记录文件*/
        [_recorder record];
        
    }else{
        NSLog(@"音频格式和文件存储格式不匹配,无法初始化Recorder");
    }
    
   
}
-(NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYYMMdd_HHmmss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}
/**
 *  添加定时器
 */
- (void)addTimer
{
     dispatch_async(dispatch_get_global_queue(0, 0), ^{
    _timer =[NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(refreshLabelText) userInfo:nil repeats:YES];
       
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
     [[NSRunLoop currentRunLoop] run];
          });
}
/**
 *  移除定时器
 */
- (void)removeTimer
{
    [_timer invalidate];
    _timer = nil;
}
-(void)refreshLabelText{
    
    self.countNum+=1;
    if (self.countNum<10) {
        dispatch_async(dispatch_get_main_queue(), ^{
        self.timeLabel.text = [NSString stringWithFormat:@"00:0%ld",(long)self.countNum];
            
              });
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
        self.timeLabel.text = [NSString stringWithFormat:@"00:%ld",(long)self.countNum];
                 });
    }
    if (self.countNum>=30) {
     
        [self stopRecord:nil];
    }
    
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
